﻿
/*******************************************************************************************
// ©2009 Microsoft Corporation.  This code is provided under the Microsoft Public License.
*******************************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Xml;
using System.Web;
using System.Xml.Serialization;

namespace ClientBilling
{
    public class CrmSystem
    {
        private static List<Client> _clients;
        private static Dictionary<string, Case> _cases = new Dictionary<string, Case>();

        static CrmSystem()
        {
            _clients = CrmSystem.BuildClientList();

            foreach (Client client in _clients)
            {
                foreach (Case clientCase in client.Cases)
                {
                    _cases.Add(clientCase.Number, clientCase);
                }
            }
        }

        public static List<Client> GetClients()
        {
            return _clients;
        }

        public static Case GetCaseByNumber(string number)
        {
            if (_cases.ContainsKey(number))
            {
                return _cases[number];
            }
            else
            {
                return null;
            }
        }

        private static List<Client> BuildClientList()
        {
            List<Client> clients = new List<Client>();

            string clientXmlRelativePath = ConfigUtility.ClientXmlRelativePath;
            string clientXmlPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + clientXmlRelativePath;

            XmlSerializer serializer = new XmlSerializer(typeof(Client));
            XmlReader reader = XmlReader.Create(clientXmlPath);

            Client newClient;

            while (reader.Read())
            {
                if (reader.Name == typeof(Client).Name)
                {
                    XmlReader clientXmlReader = reader.ReadSubtree();
                    newClient = (Client)serializer.Deserialize(clientXmlReader);
                    foreach (Case c in newClient.Cases)
                    {
                        c.Client = newClient;
                    }
                    clients.Add(newClient);
                }
            }

            return clients;
        }

        
    }
}
